import 'dart:async';

import 'package:flutter_blue/flutter_blue.dart';
import 'package:realmega_ota/history_realmega.dart';
import 'package:realmega_ota/home_realmega.dart';
import 'package:realmega_ota/realmega/history_info.dart';
import 'package:realmega_ota/realmega/history_manager.dart';
import 'package:realmega_ota/realmega/ota_manager.dart';
import 'package:realmega_ota/realmega/running_log_manager.dart';
import 'package:realmega_ota/realmega/setting_and_filter_manager.dart';
import 'package:realmega_ota/running_log_realmega.dart';
import 'package:device_preview/device_preview.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'Global.dart';
import 'util/log_util.dart';
import 'util/ble_manager.dart';

class RealmegaApp extends StatefulWidget {
  RealmegaApp({super.key}) {
    OtaManager.init();
  }

  @override
  State<StatefulWidget> createState() {
    return _RealmegaAppState();
  }
}

class _RealmegaAppState extends State<RealmegaApp> {
  DateTime? _lastPressedAt;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    Log.init();

    // _timer = Timer.periodic(const Duration(seconds: 2), (timer) {
    //   RunningLogManager.instance.addLog('请求蓝牙权限...');
    //   BleManager.getState().listen((event) {
    //     if(event == BluetoothState.on){
    //       _timer?.cancel();
    //     }
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (_lastPressedAt == null ||
              DateTime.now().difference(_lastPressedAt!) >
                  Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            _lastPressedAt = DateTime.now();
            return false;
          }
          Log.d('app exit...');
          SettingAndFilterManager.instance.writeDataToFile();
          BleManager.stopScan();
          Navigator.pop(context, true);
          return true;
        },
        child: MaterialApp(
          navigatorKey: Global.navigatorKey,
          debugShowCheckedModeBanner: false,
          color: Colors.lightBlue,
          useInheritedMediaQuery: true,
          locale: DevicePreview.locale(context),
          builder: DevicePreview.appBuilder,
          theme: ThemeData.light(),
          darkTheme: ThemeData.light(),
          home: StreamBuilder<BluetoothState>(
              stream:
                  Stream.periodic(Duration(seconds: 5)).asyncExpand((event) {
                Stream<BluetoothState> state = FlutterBlue.instance.state;
                RunningLogManager.instance.addLog('请求蓝牙权限...');
                return state;
              }),
              initialData: BluetoothState.on,
              builder: (c, snapshot) {
                final state = snapshot.data!;
                if (state == BluetoothState.on) {
                  return FindDevicesScreen();
                }
                return BluetoothOffScreen(
                  state: state,
                );
              }),
        ));
  }

  @override
  void dispose() {
    super.dispose();
  }
}

class FindDevicesScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FindDevicesScreenState();
  }
}

class _FindDevicesScreenState extends State<FindDevicesScreen> {
  int _tabIndex = 0;
  Widget _homeWidget = HomeWidget();
  Widget _historyWidget = HistoryWidget();
  Widget _logWidget = RunningLogWidget();
  List<Widget> _pageList = [];
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    BleManager.startScan();
    _pageList.clear();
    _pageList.add(_homeWidget);
    _pageList.add(_historyWidget);
    _pageList.add(_logWidget);
    _pageController = PageController(initialPage: _tabIndex, keepPage: true);

    // Timer.periodic(const Duration(seconds: 5), (timer) {
    //   HistoryManager.instance.saveHistory(HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功'));
    // });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_getPageTitle()),
        centerTitle: true,
        actions: _getAction(),
      ),
      // body: _pageList[_tabIndex],
      body: PageView(
        physics: const NeverScrollableScrollPhysics(),
        controller: _pageController,
        children: _pageList,
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            IconButton(
                onPressed: () {
                  //Fluttertoast.showToast(msg: "click home");
                  setState(() {
                    _tabIndex = 0;
                    _pageController.jumpToPage(_tabIndex);
                  });
                },
                icon: Icon(Icons.home,
                    color:
                        _tabIndex == 0 ? Colors.blueAccent : Colors.black87)),
            IconButton(
                onPressed: () {
                  //Fluttertoast.showToast(msg: "click history");
                  SettingAndFilterManager.instance.writeDataToFile();
                  setState(() {
                    _tabIndex = 1;
                    _pageController.jumpToPage(_tabIndex);
                  });
                },
                icon: Icon(Icons.history,
                    color:
                        _tabIndex == 1 ? Colors.blueAccent : Colors.black87)),
            IconButton(
                onPressed: () {
                  //Fluttertoast.showToast(msg: "click log");
                  SettingAndFilterManager.instance.writeDataToFile();
                  setState(() {
                    _tabIndex = 2;
                    _pageController.jumpToPage(_tabIndex);
                  });
                },
                icon: Icon(Icons.library_books,
                    color: _tabIndex == 2 ? Colors.blueAccent : Colors.black87))
          ],
        ),
      ),
    );
  }

  _getPageTitle() {
    if (_tabIndex == 1) {
      return 'History Record';
    } else if (_tabIndex == 2) {
      return 'Running Log';
    } else {
      return 'Device List';
    }
  }

  _getAction() {
    if (_tabIndex == 1) {
      return <Widget>[
        TextButton(
            onPressed: () {
              // Fluttertoast.showToast(msg: '清空历史记录');
              HistoryManager.instance.clearHistory();
            },
            child: Text(
              "CLEAR",
            ))
      ];
    } else if (_tabIndex == 2) {
      return <Widget>[Container()];
    } else {
      return <Widget>[
        StreamBuilder<bool>(
          stream: BleManager.isScanning(),
          initialData: false,
          builder: (c, snapshot) {
            if (snapshot.data!) {
              return TextButton(
                  onPressed: () {
                    BleManager.stopScan();
                  },
                  child: Text(
                    "STOP_SCAN",
                  ));
            } else {
              return TextButton(
                  onPressed: () {
                    BleManager.startScan();
                  },
                  child: Text(
                    "SCAN",
                  ));
            }
          },
        ),
      ];
    }
  }
}

class BluetoothOffScreen extends StatelessWidget {
  const BluetoothOffScreen({Key? key, required this.state}) : super(key: key);

  final BluetoothState state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('blueTooth'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Icon(
              Icons.bluetooth_disabled,
              size: 200.0,
              color: Colors.blue,
            ),
            Text(
              //'BLE Device ${state != null ? 'not open' : 'disabled'}.',
              '手机蓝牙状态：${state.name},请检查',
              style: Theme.of(context)
                  .primaryTextTheme
                  .bodySmall
                  ?.copyWith(color: Colors.black45),
            ),
            ElevatedButton(
                onPressed: () async {
                  BleManager.getState();
                },
                child: Text('重新检查'))
          ],
        ),
      ),
    );
  }
}
